import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Welcome from '../views/Welcome.vue';
import UserManagement from '../views/UserManagement.vue';

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/welcome', component: Welcome, meta: { requiresAuth: true } },
  { path: '/users', component: UserManagement, meta: { requiresAuth: true } },
  { path: '/permissions', component: Welcome, meta: { requiresAuth: true } },
  { path: '/products', component: Welcome, meta: { requiresAuth: true } },
  { path: '/orders', component: Welcome, meta: { requiresAuth: true } },
  { path: '/statistics', component: Welcome, meta: { requiresAuth: true } }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  if (to.meta.requiresAuth && !token) {
    ElMessage.error('请先登录');
    next('/login');
  } else {
    next();
  }
});

export default router;